/**

 @Name：管理员管理用户
 @Author：GROW
    
 */


layui.define(['table', 'form'], function(exports) {
    var $ = layui.$,
        admin = layui.admin,
        view = layui.view,
        table = layui.table,
        form = layui.form,

        //事件
        active = {
            batchdel: function() {
                var checkStatus = table.checkStatus('LAY-user-back-manage'),
                    checkData = checkStatus.data, //得到选中的数据
                    ids = [];

                if (checkData.length === 0) {
                    return layer.msg('请选择数据');
                }

                for (var i = 0; i < checkData.length; i++) {
                    if (checkData[i]['username'] === "admin") {
                        return layer.msg('admin账户无法删除');
                    }

                    if (checkData[i]['username'] === admin.userinfo.username) {
                        return layer.msg('当前账户无法删除');
                    }

                    ids.push(checkData[i]['username'])
                }

                layer.prompt({
                    formType: 1,
                    title: '敏感操作，请验证管理员密码'
                }, function(value, index) {
                    layer.close(index);

                    layer.confirm('确定删除吗？', function(index) {

                        admin.req({
                            type: 'post',
                            url: '/user/deleteUser',
                            data: { 'batchData': JSON.stringify(ids), 'password': value },
                            success: function(res) {
                                if (res.code == 0) {
                                    table.reload('LAY-user-back-manage');
                                    layer.msg('已删除');
                                } else if (res.code == 100) {
                                    return layer.msg('管理员密码错误');
                                } else {
                                    table.reload('LAY-user-back-manage');
                                    layer.msg("删除用户失败");
                                }
                            }
                        });

                        table.reload('LAY-user-back-manage');
                        layer.close(index);
                    });
                });
            },

            add: function() {
                admin.popup({
                    title: '添加新用户',
                    area: ['420px', '350px'],
                    id: 'LAY-popup-useradmin-add',
                    success: function(layero, index) {
                        view(this.id).render('manageusers/adminform').done(function() {
                            form.render(null, 'layuiadmin-form-admin');

                            //监听提交
                            form.on('submit(LAY-user-back-submit)', function(data) {
                                var field = data.field; //获取提交的字段

                                if (field["username"] === "" || field["role"] === "0") {
                                    return layer.msg("新增用户需填写用户名和角色");
                                }

                                admin.req({
                                    url: '/user/addUser',
                                    data: field,
                                    success: function(res) {
                                        if (res.code == 0) {
                                            layer.msg("新增用户成功，默认密码：" + res.data.password);
                                        } else {
                                            return layer.msg("新增用户失败");
                                        }
                                    }
                                });

                                layui.table.reload('LAY-user-back-manage'); //重载表格
                                layer.close(index); //执行关闭 
                            });
                        });
                    }
                });
            }
        };

    //管理员管理
    table.render({
        elem: '#LAY-user-back-manage',
        url: './user/getUsers',
        cols: [
            [
                { type: 'checkbox', fixed: 'left' },
                { field: 'username', title: '用户名' },
                { field: 'nickname', title: '昵称' },
                { field: 'email', title: '邮箱' },
                {
                    field: 'sex',
                    title: '性别',
                    width: 60,
                    templet: function(item) {            
                        if (item.sex == "1") return "男";              
                        else if (item.sex == "2") return "女";              
                        else return "";              
                    }
                },
                {
                    field: 'role',
                    title: '角色',
                    sort: true,
                    templet: function(item) {            
                        if (item.role == "1") return "超级管理员";              
                        else if (item.role == "2") return "数据管理员";              
                        else if (item.role == "3") return "操作员";              
                        else return "";              
                    }
                },
                { field: 'createDate', title: '创建时间', sort: true },
                { title: '操作', width: 200, align: 'center', fixed: 'right', toolbar: '#table-useradmin-admin' }
            ]
        ],
        text: { none: '暂无相关数据' },
        page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
            layout: ['prev', 'page', 'next', 'skip', 'count'], //自定义分页布局
            groups: 3 //只显示 1 个连续页码
        },
        limit: 10,
    });

    //监听工具条
    table.on('tool(LAY-user-back-manage)', function(obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            var ids = [];

            if (data['username'] === "admin") {
                return layer.msg('admin账户无法删除');
            }

            if (data['username'] === admin.userinfo.username) {
                return layer.msg('当前账户无法删除');
            }

            ids.push(data['username'])

            layer.prompt({
                formType: 1,
                title: '敏感操作，请验证管理员密码'
            }, function(value, index) {
                layer.close(index);

                layer.confirm('确定删除吗？', function(index) {

                    admin.req({
                        type: 'post',
                        url: '/user/deleteUser',
                        data: { 'batchData': JSON.stringify(ids), 'password': value },
                        success: function(res) {
                            if (res.code == 0) {
                                table.reload('LAY-user-back-manage');
                                layer.msg('已删除');
                            } else if (res.code == 100) {
                                return layer.msg('管理员密码错误');
                            } else {
                                table.reload('LAY-user-back-manage');
                                layer.msg("删除用户失败");
                            }
                        }
                    });

                    table.reload('LAY-user-back-manage');
                    layer.close(index);
                });
            });
        } else if (obj.event === 'resetpassword') {
            layer.prompt({
                formType: 1,
                title: '敏感操作，请验证管理员密码'
            }, function(value, index) {
                layer.close(index);

                layer.confirm('确定修改密码吗？', function(index) {

                    admin.req({
                        url: '/user/resetPassword',
                        data: { 'resetUser': data['username'], 'password': value },
                        success: function(res) {
                            if (res.code == 0) {
                                table.reload('LAY-user-back-manage');
                                layer.msg('已重置');
                            } else if (res.code == 100) {
                                return layer.msg('管理员密码错误');
                            } else {
                                table.reload('LAY-user-back-manage');
                                layer.msg("重置用户密码失败");
                            }
                        }
                    });

                    table.reload('LAY-user-back-manage');
                    layer.close(index);
                });
            });
        }
    });

    form.render(null, 'layadmin-useradmin-formlist');

    //监听搜索
    form.on('submit(LAY-user-back-search)', function(data) {
        var field = data.field;
        //执行重载
        table.reload('LAY-user-back-manage', {
            where: field
        });
    });

    $('.layui-btn.layuiadmin-btn-admin').on('click', function() {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    exports('useradmin', {})
});